package com.ttdevs.ttrss.ui.left;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.mcsoxford.rss.RSSFeed;
import org.mcsoxford.rss.RSSItem;
import org.mcsoxford.rss.RSSReader;
import org.mcsoxford.rss.RSSReaderException;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;

import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import com.ttdevs.ttrss.R;
import com.ttdevs.ttrss.app.AppInit;
import com.ttdevs.ttrss.bean.Source;
import com.ttdevs.ttrss.db.IDBManager;
import com.ttdevs.ttrss.ui.CustomActivity;

public class SourceFragment extends Fragment implements OnClickListener, OnChildClickListener, OnItemLongClickListener {

	private CustomActivity activity;

	private IDBManager dbm;

	private SourceExpandAdapter adapter;
	private ExpandableListView elvSubscription;

	private List<List<Source>> allList;
	private List<String> groupList;

	private ImageView ivAddSource, ivAddGroup;
	private AddSourceDialog sourceDialog;
	private AddGroupDialog groupDialog;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.activity = (CustomActivity) activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		dbm = AppInit.getDBManager();

		initData();

		sourceDialog = new AddSourceDialog(getActivity(), R.style.customDialogTheme);
		sourceDialog.setCancelable(false);

		groupDialog = new AddGroupDialog(getActivity(), R.style.customDialogTheme);
		groupDialog.setCancelable(false);

		super.onCreate(savedInstanceState);
	}

	public void initData() {
		groupList = dbm.queryAllGroup();
		if (groupList == null) {
			groupList = new ArrayList<String>();
			groupList.add("默认分组");
		}
		if (allList == null) {
			allList = new ArrayList<List<Source>>();
		}
		allList.clear();
		for (String group : groupList) {
			List<Source> list = dbm.querySource(group);
			if (list == null) {
				allList.add(new ArrayList<Source>());
			} else {
				allList.add(list);
			}
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_source, container, false);
		ivAddSource = (ImageView) view.findViewById(R.id.ivAddGroup);
		ivAddSource.setOnClickListener(this);
		ivAddGroup = (ImageView) view.findViewById(R.id.ivAddSource);
		ivAddGroup.setOnClickListener(this);

		elvSubscription = (ExpandableListView) view.findViewById(R.id.elvSubscription);
		// elvSubscription.setGroupIndicator(getResources().getDrawable(R.drawable.expander_floder));
		// elvSubscription.setDescendantFocusability(ExpandableListView.FOCUS_AFTER_DESCENDANTS);
		elvSubscription.setOnChildClickListener(this);
		elvSubscription.setOnItemLongClickListener(this);

		adapter = new SourceExpandAdapter(getActivity(), allList, groupList);
		elvSubscription.setAdapter(adapter);
		if (allList.size() > 1) {
			elvSubscription.expandGroup(1);
		}
		elvSubscription.setIndicatorBounds(GetPixelFromDips(50), GetPixelFromDips(10));
		return view;
	}

	private int GetPixelFromDips(float pixels) {
		int width = getResources().getInteger(R.integer.sliding_width);
		// Get the screen's density scale
		float scale = getResources().getDisplayMetrics().density;
		// Convert the dps to pixels, based on density scale
		return width - (int) (pixels * scale + 0.5f);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ivAddGroup:
			sourceDialog.updateGroup();
			sourceDialog.show();
			break;
		case R.id.ivAddSource:
			groupDialog.show();
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
		if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
			int groupPosition = ExpandableListView.getPackedPositionGroup(id);
			int childPosition = ExpandableListView.getPackedPositionChild(id);
			System.out.println("child onItemLongClick:" + groupPosition + "||" + childPosition);
			return true;
		}
		if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
			int groupPosition = ExpandableListView.getPackedPositionGroup(id);
			int childPosition = ExpandableListView.getPackedPositionChild(id);
			System.out.println("group onItemLongClick:" + groupPosition + "||" + childPosition);
			return true;
		}
		return false;
	}

	@Override
	public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
		activity.getSlidingMenu().toggle();
		activity.onShowResult(allList.get(groupPosition).get(childPosition).getLink());
		return false;
	}

	private class AddSourceDialog extends Dialog implements OnClickListener, OnItemSelectedListener {

		private String belongGroup = "默认分组";
		private IDBManager dbm;
		private TextView tvAlert;
		private Button btParse, btCancel, btSubmit;
		private EditText etLink, etTitle, etDescription, etOrderKey;
		private RadioButton rbYes;
		private Spinner spBelongGroup;

		private Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case -1:
					tvAlert.setText(msg.obj.toString());
					break;
				case 0:
					etTitle.setText(msg.obj.toString());
					break;
				case 1:
					etDescription.setText(msg.obj.toString());
					break;

				default:
					break;
				}
			};
		};

		public AddSourceDialog(Context context, int theme) {
			super(context, theme);
			this.dbm = AppInit.getDBManager();
		}

		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);

			this.setContentView(R.layout.dialog_add_source);

			tvAlert = (TextView) findViewById(R.id.tvAlert);
			etLink = (EditText) findViewById(R.id.etLink);
			etTitle = (EditText) findViewById(R.id.etTitle);
			etDescription = (EditText) findViewById(R.id.etDescription);
			etOrderKey = (EditText) findViewById(R.id.etOrderKey);
			rbYes = (RadioButton) findViewById(R.id.rbYes);

			btParse = (Button) findViewById(R.id.btParse);
			btCancel = (Button) findViewById(R.id.btCancel);
			btSubmit = (Button) findViewById(R.id.btSubmit);
			btParse.setOnClickListener(this);
			btCancel.setOnClickListener(this);
			btSubmit.setOnClickListener(this);

			List<String> tmpName = dbm.queryAllGroup();
			if (tmpName == null || tmpName.size() <= 0) {
				return;
			}
			String[] names = new String[tmpName.size()];
			for (int i = 0; i < tmpName.size(); i++) {
				names[i] = tmpName.get(i);
			}
			spBelongGroup = (Spinner) findViewById(R.id.spBelongGroup);
			spBelongGroup.setOnItemSelectedListener(this);
			spBelongGroup.setSelection(0, true);
			spBelongGroup.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, names));
		}

		public void updateGroup() {
			if (spBelongGroup == null) {
				return;
			}
			List<String> tmpName = dbm.queryAllGroup();
			if (tmpName == null || tmpName.size() <= 0) {
				return;
			}
			String[] names = new String[tmpName.size()];
			for (int i = 0; i < tmpName.size(); i++) {
				names[i] = tmpName.get(i);
			}
			spBelongGroup.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, names));
		}

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btParse:
				tvAlert.setText("");
				final String link = etLink.getText().toString();
				new Thread(new Runnable() {

					@Override
					public void run() {
						parseSource(link);
					}
				}).start();

				break;
			case R.id.btSubmit:
				Source src = new Source();
				src.setLink(etLink.getText().toString());
				src.setTitle(etTitle.getText().toString());
				src.setDescription(etDescription.getText().toString());
				src.setWifiautoupdate(rbYes.isChecked()); // TODO
				src.setBelonggroup(belongGroup);
				src.setOrderkey(etOrderKey.getText().toString());

				if ("".equals(src.getLink())) {
					alertError("链接不能为空");
					break;
				}
				if (dbm.addSource(src)) {
					clearForm();
					cancel();
				} else {
					alertError("插入失败");
				}
				break;
			case R.id.btCancel:
				clearForm();
				cancel();
				break;

			default:
				break;
			}
		}

		private void parseSource(String rss) {
//			try {
//				SyndFeedInput in = new SyndFeedInput();
//
//				XmlReader reader = new XmlReader(new URL(rss));
//				SyndFeed feed = in.build(reader);
//
//				Message msg = new Message();
//				msg.what = 0;
//				msg.obj = feed.getTitle();
//				handler.sendMessage(msg);
//
//				msg = new Message();
//				msg.what = 1;
//				msg.obj = feed.getDescription();
//				handler.sendMessage(msg);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
			
			try {
				RSSReader reader = new RSSReader();
				String uri = "http://mobile.csdn.net/rss_mobile.html";
				uri = rss;
				RSSFeed feed = reader.load(uri);
				
				Message msg = new Message();
				msg.what = 0;
				msg.obj = feed.getTitle();
				handler.sendMessage(msg);

				msg = new Message();
				msg.what = 1;
				msg.obj = feed.getDescription();
				handler.sendMessage(msg);
				
				reader.close();
			} catch (RSSReaderException e) {
				e.printStackTrace();
				Message msg = new Message();
				msg.what = -1;
				msg.obj = "解析失败，请确认你输入的地址正确";
				handler.sendMessage(msg);
			}
		}

		private void clearForm() {
			tvAlert.setText("");
			tvAlert.setVisibility(View.GONE);
		}

		private void alertError(String msg) {
			tvAlert.setVisibility(View.VISIBLE);
			tvAlert.setText(msg);
		}

		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			belongGroup = parent.getItemAtPosition(position).toString();
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
		}
	}

	private class AddGroupDialog extends Dialog implements OnClickListener {

		private IDBManager dbm;
		private TextView tvAlert;
		private Button btCancel, btSubmit;
		private EditText etGroupName, etOrderKey;

		public AddGroupDialog(Context context, int theme) {
			super(context, theme);
			this.dbm = AppInit.getDBManager();
		}

		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);

			this.setContentView(R.layout.dialog_add_group);

			tvAlert = (TextView) findViewById(R.id.tvAlert);
			etGroupName = (EditText) findViewById(R.id.etGroupName);
			etOrderKey = (EditText) findViewById(R.id.etOrderKey);
			btCancel = (Button) findViewById(R.id.btCancel);
			btSubmit = (Button) findViewById(R.id.btSubmit);
			btCancel.setOnClickListener(this);
			btSubmit.setOnClickListener(this);
		}

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btSubmit:
				if ("".equals(etGroupName.getText().toString())) {
					alertError("添加失败，请检查分组是否为空");
					break;
				}
				if (dbm.createGroup(etGroupName.getText().toString(), etOrderKey.getText().toString())) {
					adapter.notifyDataSetChanged();
					clearForm();
					cancel();
				} else {
					alertError("添加失败，请检查分组是否已经存在");
				}
				break;
			case R.id.btCancel:
				clearForm();
				cancel();
				break;

			default:
				break;
			}
		}

		private void clearForm() {
			etGroupName.setText("");
			etOrderKey.setText("");
			tvAlert.setText("");
			tvAlert.setVisibility(View.GONE);
		}

		private void alertError(String msg) {
			tvAlert.setVisibility(View.VISIBLE);
			tvAlert.setText(msg);
		}
	}
}